<%= hidden_field_tag input_name, '' %>
<% tags.each do |tag| %>
    <span onclick='this.remove()' class="useful-tag-badge useful-tag-badge-added">
        <%= tag.tag_name %>
        <%= hidden_field_tag input_name, tag.tag_name %>
    </span>
<% end %>

<input style='display: block;'
       type="text"
       name="entry_tags"
       autocomplete=off
       class='entry_useful_tag' value="" />
<div id='<%= options['id'] %>_all' style='position: relative;'>
    <ul style='display: none; position: absolute; width: 100%; margin: 0; padding: 5px;background: #333; color: #EEE; list-style: none;'>
        <button type='button' style='float: right;'>x</button>
        <% all_tags.each do |tag| %>
            <li style='padding: 4px;'>
                <%= tag.tag_name %>
            </li>
        <% end %>
    </ul>
</div>


<script type="text/javascript">
 (function(){
     let main_id = '#<%= options['id'] %>'
     let main = document.getElementById('<%= options['id'] %>')

     let tag_ul_show = function(){
         main.querySelectorAll('ul').forEach((ul)=>{
             ul.style.display = '';
         })
     }
     let tag_ul_hide = function(){
         main.querySelectorAll('ul').forEach((ul)=>{
             ul.style.display = 'none';
         })
     }
     let tag_input = main.querySelectorAll('.entry_useful_tag')[0]

     main.querySelectorAll('button').forEach((btn)=>{
         btn.addEventListener('click', function(){
             tag_ul_hide()
         })
     })

     /* tag_input.addEventListener('blur', function(){ */
     /* tag_ul_hide() */
     /* }) */

     tag_input.addEventListener('focus', function(){
         tag_ul_show()
     })

     let insert_tag = function(val){
             htmlString = `<span onclick='this.remove()' class="useful-tag-badge">${val}
<input type='hidden' name='<%= input_name %>' value='${val}'></span>`
             tag_input.insertAdjacentHTML('beforebegin', htmlString);
             tag_ul_hide()
     }
     main.querySelectorAll('li').forEach((li)=>{
         li.addEventListener('click', function(e){
             let val = e.target.innerText
                          console.log(val)
            insert_tag(val)
         })
     })

     tag_input.addEventListener('keypress', function(event){
         if (event.which === 13 /* Enter */) {
             console.log(tag_input)
             let val = tag_input.value
             insert_tag(val)
             event.preventDefault();
             tag_input.value = ''
         }
     })

 })()
</script>
